package com.hntech.netty.chart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * @Autho changqi.wu
 * @Date 路在脚下，使劲踩！
 */
public class NettyServer {

    private int port;

    public void start(int port) throws InterruptedException {

        this.port = port;

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();

        ServerBootstrap server = new ServerBootstrap();
        server.group(boss, work).channel(NioServerSocketChannel.class).childHandler(

                new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel serverChannel) throws Exception {
                        ChannelPipeline pipeline = serverChannel.pipeline();
                        pipeline.addLast(new StringEncoder(Charset.defaultCharset()));  //转成string
                        pipeline.addLast(new StringDecoder(Charset.defaultCharset()));
                        pipeline.addLast(new ServerBizHandler());
                    }
                }

        );


        ChannelFuture future = server.bind(this.port);
        future.channel().closeFuture().sync();
        System.out.println("server start on port " + this.port);

    }

    public static void main(String[] args) throws InterruptedException {
        new NettyServer().start(8080);

    }


}
